<template>
  <div class="products-table-wrapper">
    <!-- 批量操作区域 -->
    <div class="bulk-actions" v-if="selectedProducts.length > 0">
      <div class="selection-info">
        已选择 {{ selectedProducts.length }} 个商品
      </div>
      <div class="action-buttons">
        <button class="action-btn generate" @click="handleBulkGenerateLink">
          批量生成链接
        </button>
      </div>
    </div>

    <!-- 商品表格 -->
    <div class="products-table">
      <table>
        <thead>
          <tr>
            <th class="checkbox-col">
              <input type="checkbox" :checked="isAllSelected" :indeterminate="isIndeterminate"
                @change="toggleSelectAll" />
            </th>
            <th class="image-col">产品图片</th>
            <th class="name-col">
              <div class="sortable-header" @click="sortBy('name')">
                产品名称
                <span v-if="isSortedBy('name', 'asc')" class="sort-icon">↑</span>
                <span v-if="isSortedBy('name', 'desc')" class="sort-icon">↓</span>
              </div>
            </th>
            <th class="restaurant-col">餐厅名称</th>
            <th class="price-col">
              <div class="sortable-header" @click="sortBy('price')">
                价格
                <span v-if="isSortedBy('price', 'asc')" class="sort-icon">↑</span>
                <span v-if="isSortedBy('price', 'desc')" class="sort-icon">↓</span>
              </div>
            </th>
            <th class="commission-col">
              <div class="sortable-header" @click="sortBy('commissionRate')">
                佣金率
                <span v-if="isSortedBy('commissionRate', 'asc')" class="sort-icon">↑</span>
                <span v-if="isSortedBy('commissionRate', 'desc')" class="sort-icon">↓</span>
              </div>
            </th>
            <th class="actions-col">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="8" class="loading-row">
              <div class="loading-spinner"></div>
              <span>加载中...</span>
            </td>
          </tr>
          <template v-else>
            <tr v-for="product in paginatedProducts" :key="product.id" :class="{ 'selected': isSelected(product) }">
              <td class="checkbox-col">
                <input type="checkbox" :checked="isSelected(product)" @change="toggleSelectProduct(product)" />
              </td>
              <td class="image-col">
                <div class="product-image" @click="previewImage(product.image)">
                  <img :src="product.image" :alt="product.name" />
                </div>
              </td>
              <td class="name-col">{{ product.name }}</td>
              <td class="restaurant-col">{{ product.restaurant.name }}</td>
              <td class="price-col">
                <span class="price">{{ formatPrice(product.price) }} USDT</span>
              </td>
              <td class="commission-col">
                <span class="commission-rate">{{ formatCommissionRate(product) }}</span>
                <span class="commission-value">{{ formatPrice(calculateCommission(product)) }} USDT</span>
              </td>
              <td class="actions-col">
                <button class="action-btn small generate" @click="generateLink(product)">生成链接</button>
              </td>
            </tr>
            <tr v-if="paginatedProducts.length === 0">
              <td colspan="8" class="empty-row">
                <span>暂无商品数据</span>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="totalPages > 1">
      <button class="page-btn previous" :disabled="currentPage === 1"
        @click="currentPage = Math.max(1, currentPage - 1)">
        上一页
      </button>

      <button v-if="displayedPageNumbers[0] > 1" class="page-btn" @click="currentPage = 1">
        1
      </button>

      <span v-if="displayedPageNumbers[0] > 2" class="ellipsis">...</span>

      <button v-for="pageNum in displayedPageNumbers" :key="pageNum" class="page-btn"
        :class="{ 'active': currentPage === pageNum }" @click="currentPage = pageNum">
        {{ pageNum }}
      </button>

      <span v-if="displayedPageNumbers[displayedPageNumbers.length - 1] < totalPages - 1" class="ellipsis">...</span>

      <button v-if="displayedPageNumbers[displayedPageNumbers.length - 1] < totalPages" class="page-btn"
        @click="currentPage = totalPages">
        {{ totalPages }}
      </button>

      <button class="page-btn next" :disabled="currentPage === totalPages"
        @click="currentPage = Math.min(totalPages, currentPage + 1)">
        下一页
      </button>

      <div class="page-info">
        {{ pageStart + 1 }}-{{ pageEnd }} / {{ props.products.length }}
      </div>
    </div>

    <!-- 图片预览弹窗 -->
    <div class="image-preview-modal" v-if="previewImageUrl" @click="closePreview">
      <div class="modal-content" @click.stop>
        <button class="close-btn" @click="closePreview">×</button>
        <img :src="previewImageUrl" alt="商品预览图" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue'

interface Product {
  id: string | number;
  name: string;
  price: number;
  image: string;
  commissionRate?: number;
  restaurant: {
    name: string;
  };
}

interface SortOption {
  field: string;
  direction: 'asc' | 'desc';
}

const props = defineProps({
  // 商品数据
  products: {
    type: Array as () => Product[],
    required: true,
    default: () => []
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 初始排序设置
  initialSort: {
    type: Object as () => SortOption,
    default: () => ({ field: 'name', direction: 'asc' })
  }
})

const emit = defineEmits([
  'sort-change',        // 排序变化
  'generate-link',      // 生成链接
  'bulk-generate-link', // 批量生成链接
  'selection-change'    // 选择变化
])

// 排序状态
const sortField = ref(props.initialSort.field)
const sortDirection = ref(props.initialSort.direction)

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)

// 选择状态
const selectedProducts = ref<Product[]>([])

// 图片预览
const previewImageUrl = ref<string | null>(null)

// 监听商品数据变化，重置分页
watch(() => props.products, () => {
  currentPage.value = 1
}, { deep: true })

// 监听选择变化
watch(selectedProducts, (newValue) => {
  emit('selection-change', newValue)
}, { deep: true })

// 格式化价格显示
const formatPrice = (price: number): string => {
  return price.toFixed(2)
}

// 计算佣金
const calculateCommission = (product: Product): number => {
  return product.price * (product.commissionRate || 0.05)
}

// 格式化佣金率
const formatCommissionRate = (product: Product): string => {
  return `${((product.commissionRate || 0.05) * 100)}%`
}

// 分页计算
const totalPages = computed(() => {
  return Math.ceil(props.products.length / pageSize.value)
})

const pageStart = computed(() => {
  return (currentPage.value - 1) * pageSize.value
})

const pageEnd = computed(() => {
  return Math.min(pageStart.value + pageSize.value, props.products.length)
})

const paginatedProducts = computed(() => {
  return props.products.slice(pageStart.value, pageEnd.value)
})

// 展示的页码计算
const displayedPageNumbers = computed(() => {
  const totalDisplayPages = 5 // 最多显示5个页码
  const pages = []

  if (totalPages.value <= totalDisplayPages) {
    // 总页数少于要显示的页数，显示所有页码
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    // 总页数多于要显示的页数，显示当前页附近的页码
    let startPage = Math.max(1, currentPage.value - Math.floor(totalDisplayPages / 2))
    let endPage = startPage + totalDisplayPages - 1

    if (endPage > totalPages.value) {
      endPage = totalPages.value
      startPage = Math.max(1, endPage - totalDisplayPages + 1)
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i)
    }
  }

  return pages
})

// 排序逻辑
const sortBy = (field: string): void => {
  if (sortField.value === field) {
    // 相同字段，切换升降序
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    // 不同字段，设置为该字段的升序
    sortField.value = field
    sortDirection.value = 'asc'
  }

  emit('sort-change', { field: sortField.value, direction: sortDirection.value })
}

const isSortedBy = (field: string, direction: 'asc' | 'desc'): boolean => {
  return sortField.value === field && sortDirection.value === direction
}

// 选择逻辑
const isSelected = (product: Product): boolean => {
  return selectedProducts.value.some(p => p.id === product.id)
}

const toggleSelectProduct = (product: Product): void => {
  const index = selectedProducts.value.findIndex(p => p.id === product.id)
  if (index >= 0) {
    selectedProducts.value.splice(index, 1)
  } else {
    selectedProducts.value.push(product)
  }
}

const isAllSelected = computed(() => {
  return paginatedProducts.value.length > 0 && paginatedProducts.value.every(p => isSelected(p))
})

const isIndeterminate = computed(() => {
  return paginatedProducts.value.some(p => isSelected(p)) && !isAllSelected.value
})

const toggleSelectAll = (): void => {
  if (isAllSelected.value) {
    // 如果全选了，取消全选当前页面的商品
    paginatedProducts.value.forEach(product => {
      const index = selectedProducts.value.findIndex(p => p.id === product.id)
      if (index >= 0) {
        selectedProducts.value.splice(index, 1)
      }
    })
  } else {
    // 全选当前页面的商品
    paginatedProducts.value.forEach(product => {
      if (!isSelected(product)) {
        selectedProducts.value.push(product)
      }
    })
  }
}

// 操作按钮
const generateLink = (product: Product): void => {
  emit('generate-link', product)
}

const handleBulkGenerateLink = (): void => {
  emit('bulk-generate-link', selectedProducts.value)
}

// 图片预览
const previewImage = (imageUrl: string): void => {
  previewImageUrl.value = imageUrl
}

const closePreview = (): void => {
  previewImageUrl.value = null
}
</script>

<style lang="scss" scoped>
.products-table-wrapper {
  width: 100%;
  position: relative;

  // 批量操作区域
  .bulk-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f8f9fa;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 16px;

    .selection-info {
      font-weight: 500;
      color: #333;
    }

    .action-buttons {
      display: flex;
      gap: 12px;
    }
  }

  // 商品表格
  .products-table {
    width: 100%;
    overflow-x: auto;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    table {
      width: 100%;
      border-collapse: collapse;

      th,
      td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid #eee;

        &.checkbox-col {
          width: 40px;
        }

        &.image-col {
          width: 80px;
        }

        &.name-col {
          width: 20%;
        }

        &.restaurant-col {
          width: 15%;
        }

        &.price-col,
        &.commission-col {
          width: 12%;
        }

        &.actions-col {
          width: 15%;
        }
      }

      th {
        font-weight: 500;
        color: #666;
        background-color: #f8f9fa;

        .sortable-header {
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: space-between;

          &:hover {
            color: #333;
          }

          .sort-icon {
            margin-left: 4px;
            font-size: 12px;
          }
        }
      }

      tbody {
        tr {
          &:hover {
            background-color: #f8f9fa;
          }

          &.selected {
            background-color: rgba(25, 118, 210, 0.08);

            &:hover {
              background-color: rgba(25, 118, 210, 0.12);
            }
          }

          .loading-row,
          .empty-row {
            text-align: center;
            padding: 32px;
            color: #999;

            .loading-spinner {
              display: inline-block;
              width: 20px;
              height: 20px;
              border: 2px solid #ddd;
              border-top-color: #1976d2;
              border-radius: 50%;
              animation: spin 1s infinite linear;
              margin-right: 8px;
            }
          }
        }
      }
    }

    // 商品图片
    .product-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.2s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    // 价格展示
    .price-col {
      .price {
        display: block;
        font-weight: 500;
      }
    }

    // 佣金展示
    .commission-rate {
      display: block;
      font-weight: 500;
    }

    .commission-value {
      display: block;
      color: #4caf50;
      margin-top: 4px;
      font-size: 13px;
    }
  }

  // 分页控件
  .pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 24px;
    gap: 8px;

    .page-btn {
      min-width: 32px;
      height: 32px;
      padding: 0 8px;
      border: 1px solid #ddd;
      background-color: #fff;
      border-radius: 4px;
      cursor: pointer;

      &:hover:not(:disabled) {
        background-color: #f5f5f5;
      }

      &:disabled {
        color: #ccc;
        cursor: not-allowed;
      }

      &.active {
        background-color: #1976d2;
        color: white;
        border-color: #1976d2;
      }

      &.previous,
      &.next {
        padding: 0 12px;
      }
    }

    .ellipsis {
      color: #666;
    }

    .page-info {
      margin-left: 16px;
      color: #666;
      font-size: 14px;
    }
  }

  // 操作按钮样式
  .action-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: 500;
    transition: background-color 0.2s;

    &.discount {
      background-color: #ff9800;
      color: white;

      &:hover {
        background-color: #f57c00;
      }
    }

    &.generate {
      background-color: #2196f3;
      color: white;

      &:hover {
        background-color: #1976d2;
      }
    }

    &.small {
      padding: 4px 8px;
      font-size: 12px;
      margin-right: 8px;
    }
  }

  // 图片预览弹窗
  .image-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .modal-content {
      position: relative;
      max-width: 90%;
      max-height: 90%;
      background-color: white;
      border-radius: 8px;
      overflow: hidden;

      img {
        display: block;
        max-width: 100%;
        max-height: 80vh;
      }

      .close-btn {
        position: absolute;
        top: 12px;
        right: 12px;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: rgba(0, 0, 0, 0.6);
        color: white;
        border: none;
        font-size: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        &:hover {
          background-color: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

// 响应式布局
@media (max-width: 768px) {
  .products-table-wrapper {
    .products-table {
      table {

        th,
        td {
          &.restaurant-col {
            display: none;
          }

          &.name-col {
            width: auto;
          }
        }
      }
    }

    .bulk-actions {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
  }
}
</style>
